<template>
  <div class="test-management">
    <!-- 搜索和操作栏 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="18">
        <el-form :model="searchForm" label-width="80px" :inline="true">
          <el-form-item label="患者姓名">
            <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" />
          </el-form-item>
          <el-form-item label="检验项目">
            <el-select v-model="searchForm.testType" placeholder="请选择检验项目">
              <el-option label="全部" value="" />
              <el-option label="血常规" value="血常规" />
              <el-option label="生化全套" value="生化全套" />
              <el-option label="心电图" value="心电图" />
              <el-option label="B超" value="B超" />
              <el-option label="CT" value="CT" />
            </el-select>
          </el-form-item>
          <el-form-item label="检验结果">
            <el-select v-model="searchForm.testResult" placeholder="请选择检验结果">
              <el-option label="全部" value="" />
              <el-option label="正常" value="正常" />
              <el-option label="异常" value="异常" />
              <el-option label="待复查" value="待复查" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTest">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6" class="text-right">
        <el-button type="primary" @click="openAddDialog">新增检验记录</el-button>
        <el-button type="danger" @click="batchDelete" v-if="selectedIds.length > 0">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table
        :data="testList"
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="patientName" label="患者姓名" width="120" />
      <el-table-column prop="patientId" label="患者ID" width="120" />
      <el-table-column prop="testType" label="检验项目" width="120" />
      <el-table-column prop="testDate" label="检验日期" width="150" />
      <el-table-column prop="testResult" label="检验结果" width="120">
        <template #default="scope">
          <el-tag
              :type="scope.row.testResult === '正常' ? 'success' :
                   scope.row.testResult === '异常' ? 'danger' : 'warning'"
          >
            {{ scope.row.testResult }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="doctorName" label="检验医生" width="120" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteTest(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加/编辑检验记录对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑检验记录' : '添加检验记录'"
        width="500px"
    >
      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="80px"
      >
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="患者ID" prop="patientId">
          <el-input v-model="form.patientId" placeholder="请输入患者ID（如病历号）" />
        </el-form-item>
        <el-form-item label="检验项目" prop="testType">
          <el-select v-model="form.testType" placeholder="请选择检验项目" style="width: 100%">
            <el-option label="血常规" value="血常规" />
            <el-option label="生化全套" value="生化全套" />
            <el-option label="心电图" value="心电图" />
            <el-option label="B超" value="B超" />
            <el-option label="CT" value="CT" />
          </el-select>
        </el-form-item>
        <el-form-item label="检验日期" prop="testDate">
          <el-date-picker
              v-model="form.testDate"
              type="date"
              placeholder="选择检验日期"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="检验结果" prop="testResult">
          <el-radio-group v-model="form.testResult">
            <el-radio label="正常" />
            <el-radio label="异常" />
            <el-radio label="待复查" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检验医生" prop="doctorName">
          <el-input v-model="form.doctorName" placeholder="请输入检验医生姓名" />
        </el-form-item>
        <el-form-item label="检验备注" prop="remarks">
          <el-input
              v-model="form.remarks"
              type="textarea"
              rows="3"
              placeholder="请输入检验备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="检验记录详情"
        width="600px"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="患者姓名">{{ detailForm.patientName }}</el-descriptions-item>
        <el-descriptions-item label="患者ID">{{ detailForm.patientId }}</el-descriptions-item>
        <el-descriptions-item label="检验项目">{{ detailForm.testType }}</el-descriptions-item>
        <el-descriptions-item label="检验日期">{{ detailForm.testDate }}</el-descriptions-item>
        <el-descriptions-item label="检验结果">
          <el-tag
              :type="detailForm.testResult === '正常' ? 'success' :
                   detailForm.testResult === '异常' ? 'danger' : 'warning'"
          >
            {{ detailForm.testResult }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="检验医生">{{ detailForm.doctorName }}</el-descriptions-item>
        <el-descriptions-item label="检验备注" :span="2">{{ detailForm.remarks || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailForm.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 加载中遮罩 -->
    <div v-if="loading" class="loading-mask">
      <el-loading v-model="loading" text="加载中..." spinner="el-icon-loading"></el-loading>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// API 基础URL
const API_BASE_URL = 'http://localhost:8080'

// 状态管理
const loading = ref(false)
const errorMessage = ref('')

// 搜索表单
const searchForm = reactive({
  patientName: '',
  testType: '',
  testResult: ''
})

// 表格数据
const testList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])

// 对话框状态
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  patientName: '',
  patientId: '',
  testType: '',
  testDate: '',
  testResult: '正常',
  doctorName: '',
  remarks: ''
})

// 详情表单数据
const detailForm = reactive({
  id: '',
  patientName: '',
  patientId: '',
  testType: '',
  testDate: '',
  testResult: '',
  doctorName: '',
  remarks: '',
  createTime: '',
  updateTime: ''
})

// 表单验证规则
const rules = reactive({
  patientName: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' }
  ],
  patientId: [
    { required: true, message: '请输入患者ID', trigger: 'blur' }
  ],
  testType: [
    { required: true, message: '请选择检验项目', trigger: 'change' }
  ],
  testDate: [
    { required: true, message: '请选择检验日期', trigger: 'change' }
  ],
  testResult: [
    { required: true, message: '请选择检验结果', trigger: 'change' }
  ],
  doctorName: [
    { required: true, message: '请输入检验医生姓名', trigger: 'blur' }
  ]
})

// 页面加载时获取检验记录列表
onMounted(() => {
  fetchTestList()
})

// 获取检验记录列表
async function fetchTestList() {
  loading.value = true
  errorMessage.value = ''

  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }

    const response = await axios.get(`${API_BASE_URL}/testRecord/list`, { params })

    if (response.data.code === 200) {
      testList.value = response.data.data.records
      total.value = response.data.data.total
    } else {
      errorMessage.value = response.data.msg || '获取检验记录失败'
      ElMessage.error(errorMessage.value)
    }
  } catch (error) {
    handleApiError(error, '获取检验记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索检验记录
function searchTest() {
  currentPage.value = 1
  fetchTestList()
}

// 处理分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  fetchTestList()
}

// 处理当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
  fetchTestList()
}

// 处理选择变化
function handleSelectionChange(rows) {
  selectedIds.value = rows.map(row => row.id)
}

// 打开添加对话框
function openAddDialog() {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true

  // 聚焦到第一个输入框
  nextTick(() => {
    const input = document.querySelector('.el-dialog input[placeholder="请输入患者姓名"]')
    input?.focus()
  })
}

// 打开编辑对话框
function openEditDialog(row) {
  isEdit.value = true
  resetForm()

  // 复制数据到表单
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 打开详情对话框
function openDetailDialog(row) {
  Object.assign(detailForm, { ...row })
  detailDialogVisible.value = true
}

// 重置表单
function resetForm() {
  form.id = ''
  form.patientName = ''
  form.patientId = ''
  form.testType = ''
  form.testDate = ''
  form.testResult = '正常'
  form.doctorName = ''
  form.remarks = ''

  formRef.value?.resetFields()
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return

  formRef.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        const url = isEdit.value
            ? `${API_BASE_URL}/testRecord/update`
            : `${API_BASE_URL}/testRecord/add`

        const response = await axios.post(url, form)

        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          fetchTestList()
        } else {
          ElMessage.error(response.data.msg || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        handleApiError(error, isEdit.value ? '更新检验记录失败' : '添加检验记录失败')
      } finally {
        loading.value = false
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 删除检验记录
async function deleteTest(id) {
  try {
    const confirmResult = await ElMessageBox.confirm(
        '确定要删除该检验记录吗？此操作不可恢复',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    if (confirmResult === 'confirm') {
      loading.value = true
      const url = `${API_BASE_URL}/testRecord/delete/${id}`
      const response = await axios.delete(url)

      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        fetchTestList()
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    }
  } catch (error) {
    if (error.name !== 'CancelError') {
      handleApiError(error, '删除检验记录失败')
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
async function batchDelete() {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }

  try {
    const confirmResult = await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedIds.value.length} 条记录吗？此操作不可恢复`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    if (confirmResult === 'confirm') {
      loading.value = true
      const url = `${API_BASE_URL}/testRecord/batchDelete`
      const response = await axios.post(url, { ids: selectedIds.value })

      if (response.data.code === 200) {
        ElMessage.success('批量删除成功')
        selectedIds.value = []
        fetchTestList()
      } else {
        ElMessage.error(response.data.msg || '批量删除失败')
      }
    }
  } catch (error) {
    if (error.name !== 'CancelError') {
      handleApiError(error, '批量删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 统一处理API错误
function handleApiError(error, defaultMessage) {
  console.error('API请求错误:', error)

  if (error.response) {
    const { status, data } = error.response
    if (status === 404) {
      errorMessage.value = '接口不存在'
    } else if (status === 500) {
      errorMessage.value = '服务器内部错误'
    } else if (data && data.msg) {
      errorMessage.value = data.msg
    } else {
      errorMessage.value = `请求错误: ${status}`}
    if (error.code === 'ERR_CONNECTION_REFUSED') {
      errorMessage.value = '无法连接到服务器，请检查服务是否启动'
    } else if (error.code === 'ERR_NETWORK') {
      errorMessage.value = '网络连接失败，请检查网络设置'
    } else {
      errorMessage.value = error.message || defaultMessage
    }

    ElMessage.error(errorMessage.value)
  }

  // 格式化日期显示
  function formatDate(dateStr) {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }

  // 为表格操作列添加查看详情按钮
  // 在表格操作列模板中补充：
  // <el-button size="small" type="info" @click="openDetailDialog(scope.row)">查看</el-button>

  // 补充表格列的日期格式化显示
  // 修改检验日期列：
  // <el-table-column prop="testDate" label="检验日期" width="150">
  //   <template #default="scope">{{ formatDate(scope.row.testDate) }}</template>
  // </el-table-column>

  // 同理修改创建时间和更新时间的显示格式
  watch(() => detailForm.createTime, (val) => {
    if (val) detailForm.createTime = formatDate(val)
  })

  watch(() => detailForm.updateTime, (val) => {
    if (val) detailForm.updateTime = formatDate(val)
  })}

</script>

<style scoped>
.test-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

::v-deep .el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}

::v-deep .el-descriptions__label {
  font-weight: bold;
}

::v-deep .el-table__row:hover {
  background-color: #f0f7ff;
}

::v-deep .el-button + .el-button {
  margin-left: 8px;
}
</style>